package ts.group.webapp.market.common.core.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringUtils;

/**
 * 
 * @author jiang.zhaoxin@yahoo.com
 *
 */

public class SqlUtils {
	
	/**
	 *  由Map属性构建一批对象
	 */
	public static <T> List<T> createSimpleObjList(List<Map<String,Object>> recordList , Class<T> clazz){
		List<T> list = new ArrayList<T>();
		Map<String,Field> cache = new HashMap<String,Field>();
		Field[] fields = clazz.getDeclaredFields();
		for (Field f : fields){
			cache.put(f.getName(), f);
		}
		for(Map<String,Object> record : recordList){
			try{
				T obj = clazz.newInstance();
				for(Entry<String, Object> entry : record.entrySet()){
					String attrname = entry.getKey();
					if(cache.containsKey(attrname)){
						Field f = cache.get(attrname);
						Class<?> ftype = f.getType();
						Method method = clazz.getMethod("set"+StringUtils.capitalize(attrname), ftype);
						String ftypeName = ftype.getSimpleName();
						if(ftypeName.equals("Long")){
							Object value = entry.getValue();
							if(value!=null && StringUtils.hasText(value.toString())){
								method.invoke(obj, Long.parseLong(entry.getValue().toString()));	
							}
						}else if(ftypeName.equals("Integer")){
							Object value = entry.getValue();
							if(value!=null && StringUtils.hasText(value.toString())){
								method.invoke(obj, Integer.parseInt(entry.getValue().toString()));
							}
						}else if(ftypeName.equals("Date")){
							Object value = entry.getValue();
							if(value!=null && StringUtils.hasText(value.toString())){
								SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //yyyy/MM/dd HH:mm:ss
								method.invoke(obj, sdf.parse(value.toString()));
							}
						}else if(ftypeName.equals("BigDecimal")){
							Object value = entry.getValue();
							if(value!=null && StringUtils.hasText(value.toString())){
								method.invoke(obj, new BigDecimal(value.toString()));
							}
						}else {
							method.invoke(obj,  entry.getValue().toString());
						}
					}
				}
				list.add(obj);
		  }catch(Exception ex){
			  ex.printStackTrace();
		  }
		}
		return list;
		
	}
	
	/**
	 *   由Map属性构建一个对象
	 */
	public static <T> T createSimpleObj(Map<String,Object> record , Class<T> clazz){
		Map<String,Field> cache = new HashMap<String,Field>();
		Field[] fields = clazz.getDeclaredFields();
		for (Field f : fields){
			cache.put(f.getName(), f);
		}
		T obj = null;
		try{
			obj = clazz.newInstance();
			for(Entry<String, Object> entry : record.entrySet()){
				String attrname = entry.getKey();
				if(cache.containsKey(attrname)){
					Field f = cache.get(attrname);
					Class<?> ftype = f.getType();
					Method method = clazz.getMethod("set"+StringUtils.capitalize(attrname), ftype);
					String ftypeName = ftype.getSimpleName();
					if(ftypeName.equals("Long")){
						Object value = entry.getValue();
						if(value!=null && StringUtils.hasText(value.toString())){
							method.invoke(obj, Long.parseLong(entry.getValue().toString()));	
						}
					}else if(ftypeName.equals("Integer")){
						Object value = entry.getValue();
						if(value!=null && StringUtils.hasText(value.toString())){
							method.invoke(obj, Integer.parseInt(entry.getValue().toString()));
						}
					}else if(ftypeName.equals("Date")){
						Object value = entry.getValue();
						if(value!=null && StringUtils.hasText(value.toString())){
							SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							method.invoke(obj, sdf.parse(value.toString()));
						}
					}else if(ftypeName.equals("BigDecimal")){
						Object value = entry.getValue();
						if(value!=null && StringUtils.hasText(value.toString())){
							method.invoke(obj, new BigDecimal(value.toString()));
						}
					}else {
						method.invoke(obj,  entry.getValue().toString());
					}
				}
		}}catch(Exception ex){
			ex.printStackTrace();
		}
		return obj;
	}
	
	/**
	 * 获取测试卡工单流水号
	 * @rule : 获取四位主键
	 * @return
	 */
	public static String getUniqueSerialNumberFromCardSheet(JdbcTemplate jt){
		    StringBuffer sb = new StringBuffer();
	        Date date = new Date();
	        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
	        String str = format.format(date);
	        sb.append(str);
	        Integer maxInt = jt.queryForInt("SELECT MAX(CARD_SHEET_ID) FROM t_eom_card_sheet");
	        String  suffix = String.format("%04d",maxInt+1);
	        sb.append(suffix);
		return sb.toString();
	}
	/**
	 * 获取重保申请单号
	 * @rule : 获取四位主键
	 * @return
	 */
	public static String getUniqueSerialNumberFromKeyTaskApply(JdbcTemplate jt){
		    StringBuffer sb = new StringBuffer();
	        Date date = new Date();
	        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
	        String str = format.format(date);
	        sb.append(str);
	        Integer maxInt = jt.queryForInt("SELECT MAX(APPLICATION_FORM_ID)  FROM t_eom_key_application_info");
	        String  suffix = String.format("%04d",maxInt+1);
	        sb.append(suffix);
		return sb.toString();
	}
	/**
	 * sql 转换成List<Map<String>>
	 * @param sql
	 * @param startIndex
	 * @param pageNumber
	 * @param pageSize
	 * @param jTemplate
	 * @return
	 */
	public static List<Map<String,Object>> convertSqlToMap(String sql, int startIndex , int pageNumber, int pageSize,JdbcTemplate jTemplate){
		if (jTemplate == null) {
			throw new IllegalArgumentException(
					"jdbcTemplate不能为空. ");
		} else if (sql == null || sql.equals("")) {
			throw new IllegalArgumentException(
					"SQL语句不能为空 ");
		}
		
		//String sqlBak = sql.toLowerCase();
		//String searchValue = " from ";
		//String countSQL = "select count(*) from ("+sqlBak+") T";
		
		//int sqlCount = jTemplate.queryForInt(countSQL);
		
		StringBuffer paginationSQL = new StringBuffer(" ");
		paginationSQL.append(sql);
		paginationSQL.append(" limit "+ startIndex+","+pageSize);
		List<Map<String,Object>> resultList = jTemplate.queryForList(paginationSQL.toString());
		
		return resultList;
	}
 }

